package views;

import utils.ConnDB;
import utils.DataUtil;

import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.SQLException;

public class RecordPanel extends JPanel {
    private JTable table;

    String[] header = {"序号", "选课编号","学生名字","学号","年级", "课程名称", "任教老师"};

    /**
     * Create the panel.
     */
    public RecordPanel() {
        setLayout(null);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(27, 30, 728, 380);
        add(scrollPane);

        table = new JTable();
        scrollPane.setViewportView(table);
        tableInit();

        // 添加刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.setBounds(650, 420, 100, 30); // 根据实际位置调整
        add(refreshButton);

        // 点击刷新按钮时重新加载表格数据
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tableInit();
            }
        });
    }

    private void tableInit() {
        String sql = "SELECT\n" +
                "\trecord.id,\n" +
                "\trecord.student_name,\n" +
                "\trecord.card,\n" +
                "\trecord.grade,\n" +
                "\tcourse.NAME,\n" +
                "\tcourse.teacher \n" +
                "FROM\n" +
                "\trecord\n" +
                "\tLEFT JOIN course ON course.id = record.cource_id";
        try {
            table.setModel(new DefaultTableModel(
                    DataUtil.getSetArrays(ConnDB.executeQuery(sql)), header
            ));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
